package com.socket3;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by sh04799 on 2017/10/19.
 */

public class SockketServerThread extends Thread {
	private int mPort;
	private ServerSocket serverSocket;
	private Socket socket;
//	BufferedReader reader;
	BufferedWriter writer;

	private BufferedInputStream inputStream;

	public SockketServerThread(int port) {
		this.mPort = port;
		try {
			serverSocket = new ServerSocket(mPort);
			socket = serverSocket.accept();
//			reader = new BufferedReader(new InputStreamReader(
//					socket.getInputStream()));
			inputStream = new BufferedInputStream(socket.getInputStream());
			writer = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			System.out.println("run:isConnected " + socket.isConnected());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				// 读
//				char[] buf = new char[2048];
//				int length = reader.read(buf);
//				System.out.println("the length is " + buf[0] + length);
//				String content = new String(buf);
//				System.out.println("===" + content);
//				// 写
//				writer.write("aa");
//				writer.flush();
//				Thread.sleep(500);
				
				 //自己定义一个缓冲区
	            byte[] buffer=new byte[1024];
	            int length=inputStream.read(buffer);
	            System.out.println("length=="+length);
//	            for(int i=0;i<buffer.length;i++){
//	            	System.out.println(buffer[i]);
//	            }
	            System.out.println("buff=="+new String(buffer));

			} catch (IOException  e) {
				e.printStackTrace();
			}

		}

	}

}
